#!/bin/bash
# Arch Linux 启动问题诊断和修复脚本
# 在 Live USB 环境中运行

set -e

echo "========================================="
echo "  Arch Linux 启动问题完整诊断"
echo "========================================="
echo ""

# 颜色定义
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 检查函数
check_file() {
    if [ -f "$1" ]; then
        echo -e "${GREEN}✓${NC} $1 存在"
        return 0
    else
        echo -e "${RED}✗${NC} $1 缺失"
        return 1
    fi
}

echo "=== 第 1 步：挂载系统 ==="
echo "挂载 Btrfs 根子卷..."
mount -o subvol=@ /dev/sda2 /mnt || { echo "挂载根分区失败"; exit 1; }

echo "挂载 EFI 分区..."
mount /dev/sda1 /mnt/boot/efi || { echo "挂载 EFI 分区失败"; exit 1; }

echo -e "${GREEN}✓${NC} 系统挂载完成"
echo ""

echo "=== 第 2 步：检查 EFI 分区结构 ==="
echo ""
echo "EFI 分区完整目录树："
tree /mnt/boot/efi 2>/dev/null || find /mnt/boot/efi -print
echo ""

echo "=== 第 3 步：检查关键启动文件 ==="
BOOTX64_OK=false
SYSTEMD_OK=false

check_file "/mnt/boot/efi/EFI/BOOT/BOOTX64.EFI" && BOOTX64_OK=true
check_file "/mnt/boot/efi/EFI/systemd/systemd-bootx64.efi" && SYSTEMD_OK=true
echo ""

echo "=== 第 4 步：检查 Bootloader 配置 ==="
echo ""
echo "--- loader.conf ---"
if check_file "/mnt/boot/efi/loader/loader.conf"; then
    cat /mnt/boot/efi/loader/loader.conf
else
    echo -e "${RED}配置文件缺失！${NC}"
fi
echo ""

echo "--- arch.conf ---"
if check_file "/mnt/boot/efi/loader/entries/arch.conf"; then
    cat /mnt/boot/efi/loader/entries/arch.conf
else
    echo -e "${RED}启动条目缺失！${NC}"
fi
echo ""

echo "=== 第 5 步：检查内核文件 ==="
check_file "/mnt/boot/vmlinuz-linux"
check_file "/mnt/boot/initramfs-linux.img"
echo ""

echo "=== 第 6 步：检查分区信息 ==="
echo ""
echo "EFI 分区 (sda1):"
blkid /dev/sda1
echo ""
echo "根分区 (sda2):"
blkid /dev/sda2
echo ""

echo "当前挂载状态："
findmnt /mnt
findmnt /mnt/boot/efi
echo ""

echo "========================================="
echo "  诊断完成"
echo "========================================="
echo ""

# 判断是否需要修复
NEEDS_REPAIR=false

if [ "$BOOTX64_OK" = false ] || [ "$SYSTEMD_OK" = false ]; then
    NEEDS_REPAIR=true
    echo -e "${RED}⚠ 检测到 bootloader 文件缺失${NC}"
fi

if [ ! -f "/mnt/boot/efi/loader/loader.conf" ] || [ ! -f "/mnt/boot/efi/loader/entries/arch.conf" ]; then
    NEEDS_REPAIR=true
    echo -e "${RED}⚠ 检测到配置文件缺失${NC}"
fi

echo ""
if [ "$NEEDS_REPAIR" = true ]; then
    echo -e "${YELLOW}建议执行修复步骤${NC}"
    echo ""
    echo "是否立即修复？(y/n)"
    read -r response
    if [[ "$response" =~ ^([yY][eE][sS]|[yY])$ ]]; then
        echo ""
        echo "=== 开始修复 ==="
        echo ""
        
        # 进入 chroot
        echo "进入 chroot 环境..."
        arch-chroot /mnt /bin/bash << 'CHROOT_EOF'
set -e

echo "=== 重新安装 systemd-boot ==="
# 先尝试移除（可能会失败，忽略错误）
bootctl remove 2>/dev/null || true

# 强制安装
bootctl install --force

echo ""
echo "=== 修复权限 ==="
chmod 700 /boot/efi
chmod 600 /boot/efi/loader/random-seed 2>/dev/null || true

echo ""
echo "=== 重新创建配置文件 ==="

# 获取 PARTUUID
PARTUUID=$(blkid -s PARTUUID -o value /dev/sda2)

# 创建 loader.conf
cat > /boot/efi/loader/loader.conf << EOF
default arch.conf
timeout 3
console-mode max
editor no
EOF

# 创建 arch.conf
cat > /boot/efi/loader/entries/arch.conf << EOF
title   Arch Linux
linux   /vmlinuz-linux
initrd  /initramfs-linux.img
options root=PARTUUID=$PARTUUID rw rootflags=subvol=@ quiet
EOF

echo ""
echo "=== 验证配置 ==="
echo "--- loader.conf ---"
cat /boot/efi/loader/loader.conf
echo ""
echo "--- arch.conf ---"
cat /boot/efi/loader/entries/arch.conf
echo ""

echo "=== 验证文件 ==="
ls -lh /boot/efi/EFI/BOOT/BOOTX64.EFI
ls -lh /boot/efi/EFI/systemd/systemd-bootx64.efi
ls -lh /boot/vmlinuz-linux
ls -lh /boot/initramfs-linux.img

echo ""
echo "修复完成！"

CHROOT_EOF

        echo ""
        echo -e "${GREEN}=========================================${NC}"
        echo -e "${GREEN}  修复完成！${NC}"
        echo -e "${GREEN}=========================================${NC}"
        echo ""
        echo "请执行以下命令重启系统："
        echo ""
        echo "  umount -R /mnt"
        echo "  reboot"
        echo ""
        echo "重启后记得移除 ISO 文件！"
        
    else
        echo "修复已取消。"
    fi
else
    echo -e "${GREEN}✓ 所有文件完整，无需修复${NC}"
    echo ""
    echo "如果仍然无法启动，请检查："
    echo "1. VirtualBox 设置中 '启用 EFI' 是否勾选"
    echo "2. 启动顺序是否正确"
    echo "3. ISO 文件是否已移除"
fi

echo ""
echo "========================================="

